const app = getApp()
const db = wx.cloud.database();
const _ = db.command;
// const com = require("../../utils/com.js");
// 插屏广告
let interstitialAd = null;
// 激励视频广告
let rewardedVideoAd = null;
Page({
  data: {
    delta: 0,
    openid: '',
    userInfo: null,
    period: null,
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    Custom: app.globalData.Custom,
    signNum: 0,
    signTime: '',
    luckNum: 0,
    votePoint: 0,
    TabCur: 0,
    // 偶像信息
    idolId: '',
    idol: {},
    listWeek: [],
    listMonth: [],
    list: [],
    load: true
  },
  onLoad: function (options) {
    let that = this,
      idolId = options.id;
    let pages = getCurrentPages();
    let pageLen = pages.length - 1;
    console.log("页面深度 " + pageLen);
    that.setData({
      delta: pageLen
    })
    if (idolId) {
      // 加载明星信息
      db.collection('ad_idol').doc(idolId).get({
        success: res => {
          console.log("加载明星信息")
          console.log(res.data)
          that.setData({
            idolId: idolId,
            idol: res.data
          })
        },
        fail: res => {
          console.error(res)
        }
      })
      /////////////
      // 加载周期信息
      app.getPeriod(function (period) {
        console.log("加载周期")
        console.log(period)
        that.setData({
          period: period
        })
        console.log('rankUsers')
        wx.cloud.callFunction({
          name: 'rankUsers',
          data: {
            week: period.week,
            idolId: idolId
          },
          complete: res => {
            console.log(res)
            that.setData({
              listWeek: res.result.list
            })
          }
        })
        wx.cloud.callFunction({
          name: 'rankUsers',
          data: {
            month: period.month,
            idolId: idolId
          },
          complete: res => {
            console.log(res)
            that.setData({
              listMonth: res.result.list
            })
          }
        })
      });

      //////

    } else {
      console.log("id为空，返回首页")
      wx.reLaunch({
        url: '/pages/index/index'
      })
    }
    that.onShareAppMessage();
    // 加载慢，测试是注释掉
    that.loadAd();
  },
    /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    // 加载访问者信息
    app.getOpenid(function (result) {
      that.setData({
        openid: result
      })
      app.getUserInfo1(function (result2) {
        that.setData({
          userInfo: result2
        })
      }, result)
      app.getTaskCount(function (result3) {
        console.log(result3)
        that.setData({
          signNum: result3.signNum,
          signTime: result3.signTime,
          luckNum: result3.luckNum
        })
      }, result)
    })
    ////////////////////////////
  },
    /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  /**
   * 获取用户授权信息
   * @param {*} e 
   */
  getUserProfile(e) {
    let that = this;
    app.userReg(function (userInfo) {
      that.setData({
        userInfo: userInfo,
        hasUserInfo: true
      })
      // 分发按钮
      let target = e.currentTarget.dataset.target;
      if (target == 'DialogModal1') {
        that.showModal(e);
      }
      if (target == 'viewVideo') {
        that.viewVideo(e);
      }
      if (target == 'goLuck') {
        that.goLuck(e);
      }
      if (target == 'signToday') {
        that.signToday(e);
      }
    });
  },
  loadAd() {
    let that = this;
    // 插屏广告
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({ adUnitId: 'adunit-3e132134b2d581b9' })
      interstitialAd.onLoad(() => {
        console.log('onLoad 插屏广告')
      })
      interstitialAd.onError((err) => {
        console.log('onError 插屏广告', err)
      })
      interstitialAd.onClose((res) => {
        console.log('onClose 插屏广告', res)
      })
    }
    // 激励视频广告
    let point = 30;
    if (wx.createRewardedVideoAd) {
      rewardedVideoAd = wx.createRewardedVideoAd({ adUnitId: 'adunit-e2ae279c123bb5ae' })
      rewardedVideoAd.onLoad(() => {
        console.log('onLoad 激励视频广告')
      })
      rewardedVideoAd.onError((err) => {
        console.log('onError 激励视频广告', err)
      })
      rewardedVideoAd.onClose(res => {
        // 用户点击了【关闭广告】按钮
        if (res && res.isEnded) {
          // 正常播放结束，可以下发游戏奖励 gotPoint: function (callBack, openid, ptype, point) {
          app.gotPoint(function (result) {
            wx.showToast({
              title: '获得积分 +' + point,
              icon: 'success'
            })
          }, that.data.openid, 3, point);
        } else {
          // 播放中途退出，不下发游戏奖励
        }
      })
    }
    // 激励视频广告 结束
  },

  ///////////////////////////////////
  showModal(e) {
    this.setData({
      votePoint: this.data.userInfo.point || 0,
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  listenerSlider: function (e) {
    this.setData({
      votePoint: e.detail.value
    })
  },
  goLuck: function (e) {
    wx.navigateTo({
      url: '/pages/luck/luck',
    })
  },
  BackPage() {
    wx.navigateBack({
      delta: 1
    });
  },
  toHome(){
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },
  /**投票  */
  voteIdol: function () {
    // gotVote: function (callBack, openid, idol_id, point) {
    let that = this,
      openid = that.data.openid,
      idolId = that.data.idolId,
      point = that.data.votePoint;
    wx.showLoading({
      title: '投票中',
      mask: true
    })
    app.gotVote(function (res) {
      console.log("detail.js");
      console.log(res);
      // 加粉丝
      app.addFans(function (result) { }, openid, idolId, point);
      // 重载用户信息
      app.getUserInfo1(function (result2) {
        that.setData({
          userInfo: result2
        })
      }, openid);
      that.hideModal();
      wx.hideLoading();
      wx.showToast({
        title: '投票成功！',
        icon: 'success'
      })
    }, openid, idolId, point);
  },

  // 签到 use
  signToday: function (e) {
    console.log("signToday");
    let that = this, point = 5;
    wx.showLoading({
      title: '签到中',
      mask: true
    })
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })
    }
    let time = app.nowTimeStamp()
    db.collection('ad_point_logs').add({
      data: {
        // "_openid": "",
        type: 1,
        create_time: time,
        point: point,
        week: 1,
        month: 1,
      },
      success: res => {
        // app.addPoint(app.globalData.setting.signPoint);addPoint: function (callBack, openid, point) 
        app.addPoint(function (result) {
          console.log(result)
        }, that.data.openid, point);
        wx.hideLoading()
        that.setData({
          signNum: that.data.signNum + 1,
          signTime: app.formatDateTime(time)
        })
        wx.showToast({
          title: '签到成功 +' + point,
          icon: 'success'
        })
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          title: '签到失败',
          icon: 'none'
        })
      }
    })
  },
  // 看视频广告
  viewVideo: function (e) {
    if (rewardedVideoAd) {
      rewardedVideoAd.show()
        .catch(() => {
          rewardedVideoAd.load()
            .then(() => rewardedVideoAd.show())
            .catch(err => {
              console.log('激励视频 广告显示失败')
            })
        })
    } else {
      wx.showToast({
        title: '暂无广告',
        icon: 'none'
      })
    }
  },

  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id
      // ,MainCur: e.currentTarget.dataset.id
      // ,VerticalNavTop: (e.currentTarget.dataset.id - 1) * 50
    })
  }

})